package top.lshaci.learning.oauth2.gateway.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONObject;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

/**
 * WebUtil
 *
 * @author lshaci
 * @since 1.0.0
 */
public class WebUtil {

    public static Mono writeToResponse(ServerHttpResponse response, int code, String msg) {
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.getHeaders().set("Access-Control-Allow-Origin", "*");
        response.getHeaders().set("Cache-Control", "no-cache");
        JSONObject json = new JSONObject();
        json.set("code", code);
        json.set("msg", msg);
        String body = json.toString();
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(CharsetUtil.CHARSET_UTF_8));
        return response.writeWith(Mono.just(buffer))
                .doOnError(error -> DataBufferUtils.release(buffer));
    }

}
